<template>
  <el-dialog :title="action === 'add' ? '新增' : '修改'" width="40%" draggable 
              :close-on-click-modal="false" v-model="visible" @open="submitted = false">
    <el-form class="data-form" :model="dataForm" :rules="dataRule" ref="dataFormRef" @keyup.enter="dataFormSubmit(dataFormRef)" label-width="80px">
      <el-form-item label="登录帐号" prop="username">
        <el-input v-model="dataForm.username" placeholder="登录帐号"></el-input>
      </el-form-item>
      <el-form-item label="用户姓名" prop="fullname">
        <el-input v-model="dataForm.fullname" placeholder="用户姓名"></el-input>
      </el-form-item>
      <el-form-item label="部门" prop="departId">
        <el-input placeholder="请选择部门" v-model="depart.name" @focus="openDepartDialogEvent">
          <template #append>
            <el-button><icon-svg name="search" /></el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="角色" prop="phone">
        <el-select style="width: 100%" v-model="role.ids" multiple filterable placeholder="请选择">
          <el-option v-for="item in role.dataList" :key="item.id" :label="item.name" :value="item.id">
            <span style="float: left">{{ item.name }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px; padding-right: 20px">{{ item.code }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="邮箱" prop="mail">
        <el-input v-model="dataForm.mail" placeholder="邮箱"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="dataForm.phone" placeholder="手机号"></el-input>
      </el-form-item>
      <el-form-item label="状态" size="small" prop="status">
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="'0'">禁用</el-radio>
          <el-radio :label="'1'">正常</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="ad-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit(dataFormRef)" :disabled="submitted">确定</el-button>
      </div>
    </template>
    <depart-tree v-if="depart.visible" ref="departTreeRef" @selectDepartEvent="selectDepartEvent"></depart-tree>
  </el-dialog>
</template>

<script lang="ts" setup>
import http from "@/utils/httpRequest";
import validate from "@/utils/validate";
import type { FormInstance } from "element-plus";
import { ref, reactive, nextTick, defineExpose, defineEmits } from "vue";

import DepartTree from "./depart-tree.vue";

// 操作：add-新增，update-修改
const action = ref("");

// 弹窗是否显示
const visible = ref(false);

// 提交状态
const submitted = ref(false);

// 表单数据
const dataForm = reactive({
  id: 0,
  username: "",
  fullname: "",
  mail: "",
  phone: "",
  status: "1",
});

// 部门选择树引用
const departTreeRef = ref();

// 表单引用
const dataFormRef = ref<FormInstance>();

// 角色相关信息
const role = reactive({
  // 用户角色信息
  ids: [],
  // 角色列表
  dataList: [],
});

// 部门相关信息
const depart = reactive({
  id: "",
  name: "",
  visible: false,
});

// 数据校验规则
const dataRule = reactive({
  username: validate.username(true),
  fullname: validate.fullname(true),
  mail: validate.email(),
  phone: validate.phone(),
});

// 父级组件的自定义事件
const emit = defineEmits([ 'loadTableData' ]);

// 表单初始化
const initForm = async (a, d) => {
  action.value = a;
  await nextTick();
  visible.value = true;
  // 新增操作
  if (a === "add") {
    http
      .post({
        url: "/user/roles",
      })
      .then(({ data }) => {
        if (http.success(data)) {
          visible.value = true;
          dataFormRef.value.resetFields();
          role.ids = [];
          role.dataList = data.body;
        }
      });
    return;
  }
  // 修改操作
  dataForm.id = d.id;
  http
    .post({
      url: "/user/info",
      params: { userId: dataForm.id },
    })
    .then(async ({ data }) => {
      if (http.success(data)) {
        visible.value = true;
        await nextTick();
        dataFormRef.value.resetFields();
        // 角色信息
        role.ids = data.body.ids;
        // 角色列表
        role.dataList = data.body.roleList;
        // 用户表单信息
        let user = data.body.user;
        dataForm.id = user.id;
        dataForm.username = user.username;
        dataForm.fullname = user.fullname;
        dataForm.mail = user.mail;
        dataForm.phone = user.phone;
        dataForm.status = user.status;
        depart.id = user.departId;
        depart.name = user.departName;
      }
    });
};

// 打开选择部门窗口
const openDepartDialogEvent = async () => {
  depart.visible = true;
  await nextTick();
  departTreeRef.value.init(depart.id);
};

// 选择部门事件
const selectDepartEvent = (node) => {
  depart.id = node.id;
  depart.name = node.name;
};

// 表单提交
const dataFormSubmit = (form: FormInstance | undefined) => {
  if (submitted.value) {
    return;
  }
  if (!form) {
    return;
  }
  form.validate((valid) => {
    if (valid) {
      submitted.value = true;
      http
        .post({
          url: "/user/save",
          data: {
            id: dataForm.id || undefined,
            username: dataForm.username,
            fullname: dataForm.fullname,
            mail: dataForm.mail || undefined,
            phone: dataForm.phone || undefined,
            status: dataForm.status,
            departId: depart.id || undefined,
            roleIds: role.ids,
          }
        })
        .then(({data}) => {
          if (http.success(data)) {
            visible.value = false;
            emit("loadTableData");
          }
          submitted.value = false;
        });
    }
  });
};

// 暴露方法
defineExpose({ initForm });
</script>
